1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
/*!
A disjoint-set forest based data structure for simultaneously hash-consing and equality-checking terms
*/
use super::*;

/// A standard context for hash-consing and equality checking
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct DisjointSetCtx {
    /// A table mapping terms to their parents in a disjoint set forest
    table: IndexMap<TermId, Node, BuildHasherDefault<PassThroughHasher>>,
}

/// A node in a standard context
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
struct Node {
    parent: usize,
    rank: u8,
    is_ty: bool,
    is_root_term: bool,
}

impl Node {
    /// Create a new node with no parent or rank
    #[inline]
    pub const fn new(is_ty: bool, is_root_term: bool) -> Node {
        Node {
            parent: std::usize::MAX,
            rank: 0,
            is_ty,
            is_root_term,
        }
    }

    /// Set the parent index of this node
    #[inline]
    pub fn set_parent(&mut self, parent: usize) -> &mut Node {
        self.parent = parent;
        self
    }

    /// Set the rank of this node
    #[inline]
    pub fn set_rank(&mut self, rank: u8) -> &mut Node {
        self.rank = rank;
        self
    }

    /// Set that this node is a type
    #[inline]
    pub fn set_ty(&mut self, is_ty: bool) {
        self.is_ty = is_ty
    }

    /// Get the parent index of this node
    #[inline]
    const fn parent(self) -> usize {
        self.parent
    }

    /// Get the rank of this node
    #[inline]
    const fn rank(self) -> u8 {
        self.rank
    }

    /// Get whether this node is a type
    #[inline]
    const fn is_ty(self) -> bool {
        self.is_ty
    }

    /// Get whether this term has precedence over another
    #[inline]
    const fn has_precedence(&self, other: &Node) -> bool {
        self.is_root_term > other.is_root_term
            || (self.is_ty == other.is_ty && self.rank > other.rank)
    }
}

impl DisjointSetCtx {
    /// Get the size of this context
    #[inline]
    pub fn len(&self) -> usize {
        self.table.len()
    }

    /// Get the representative for a index, *without* path compression
    #[inline]
    fn get_repr_index(&self, mut ix: usize) -> usize {
        let mut result = ix;
        while let Some((_, &node)) = self.table.get_index(ix) {
            result = ix;
            ix = node.parent();
        }
        debug_assert_eq!(ix, usize::MAX);
        result
    }

    /// Get the representative for a *valid* index, *with* path compression
    #[inline]
    fn get_repr_index_mut(&mut self, ix: usize) -> usize {
        // Get the parent of this index, if any
        let parent = if let Some((_, &node)) = self.table.get_index(ix) {
            node.parent()
        } else {
            // This index has no parent, so should be usize::MAX
            debug_assert_eq!(ix, usize::MAX);
            return ix;
        };
        // If this index's parent is usize::MAX, it's a root, so it's own representative
        if parent == std::usize::MAX {
            return ix;
        }
        // Otherwise, get the parent's representative recursively
        let parent_repr = self.get_repr_index_mut(parent);
        debug_assert_ne!(parent_repr, usize::MAX);
        // Now, set the current parent to the parent's representative
        let (_, node) = self.table.get_index_mut(ix).expect(
            "Calls to get_repr_index_mut should never change the indices of the underlying hashmap",
        );
        // Set the parent of this node; this needs no rank updates
        node.set_parent(parent_repr);
        // And return the representative
        parent_repr
    }

    /// Get the representative for a term, *without* path compression
    #[inline]
    fn get_repr_term(&self, term: &Term) -> Option<usize> {
        if let Some(index) = self.table.get_index_of(term) {
            Some(self.get_repr_index(index))
        } else {
            None
        }
    }

    /// Get the representative for a term, *with* path compression
    #[inline]
    fn get_repr_term_mut(&mut self, term: &Term) -> Option<usize> {
        if let Some(index) = self.table.get_index_of(term) {
            Some(self.get_repr_index_mut(index))
        } else {
            None
        }
    }

    /// Shallow cons a term, returning it's new index and it's value, if different from the input
    #[inline]
    fn shallow_cons_index(&mut self, id: &TermId) -> (usize, Option<TermId>) {
        match self.table.get_full(id) {
            Some((index, consed, _)) => {
                if id.ptr_eq(consed) {
                    (index, None)
                } else {
                    (index, Some(consed.clone()))
                }
            }
            None => {
                let (index, old) = self.table.insert_full(
                    id.clone(),
                    Node::new(id.is_local_ty().unwrap_or(false), id.is_root()),
                );
                debug_assert_eq!(old, None);
                (index, None)
            }
        }
    }

    /// Merge indices, returning if they were already merged
    #[inline]
    fn merge_indices(&mut self, left_ix: usize, right_ix: usize) -> bool {
        if left_ix == right_ix {
            return true;
        }
        let left_repr = self.get_repr_index_mut(left_ix);
        let right_repr = self.get_repr_index_mut(right_ix);
        if left_repr == right_repr {
            return true;
        }
        let left_node = self
            .table
            .get_index(left_repr)
            .expect("Left representative must be valid index")
            .1;
        let left_rank = left_node.rank();
        let left_is_ty = left_node.is_ty();
        let right_node = self
            .table
            .get_index(right_repr)
            .expect("Right representative must be valid index")
            .1;
        let right_rank = right_node.rank();
        let right_is_ty = right_node.is_ty();
        let (parent, child, parent_rank) = if right_node.has_precedence(left_node) {
            (right_repr, left_repr, right_rank)
        } else {
            (left_repr, right_repr, left_rank.max(right_rank + 1))
        };
        let is_ty = left_is_ty || right_is_ty;
        self.table
            .get_index_mut(child)
            .expect("Child must be valid index")
            .1
            .set_parent(parent)
            .set_ty(is_ty);
        self.table
            .get_index_mut(parent)
            .expect("Parent must be valid index")
            .1
            .set_rank(parent_rank)
            .set_ty(is_ty);
        false
    }

    /// Get whether two representations are equal
    fn repr_eq(&self, left: usize, right: usize) -> Option<bool> {
        if left == right {
            return Some(true);
        }
        let left_val = self
            .table
            .get_index(left)
            .expect("get_repr_term_mut always returns a valid index")
            .0;
        let right_val = self
            .table
            .get_index(right)
            .expect("get_repr_term_mut always returns a valid index")
            .0;
        let result = left_val.eq_in(right_val, &mut Typed);
        debug_assert_ne!(
            result,
            Some(true),
            "Have {:#?} == {:#?} with unequal representations {} {}",
            left_val,
            right_val,
            left,
            right
        );
        result
    }
}

impl ConsCtx for DisjointSetCtx {
    #[inline]
    fn is_pointer_cons(&self) -> bool {
        true
    }

    #[inline]
    fn shallow_cons(&mut self, id: &TermId) -> Option<TermId> {
        self.shallow_cons_index(id).1
    }

    #[inline]
    fn try_cons(&self, id: &Term) -> Result<Option<TermId>, ()> {
        if let Some((consed, _)) = self.table.get_key_value(id) {
            if consed.as_ptr() == id as *const Term {
                Ok(None)
            } else {
                Ok(Some(consed.clone()))
            }
        } else {
            Err(())
        }
    }

    #[inline]
    fn check_cons(&self, id: &Term) -> bool {
        if let Some((consed, _)) = self.table.get_key_value(id) {
            consed.as_ptr() == id as *const Term
        } else {
            false
        }
    }

    #[inline]
    fn uncons(&self, code: Code) -> Option<TermId> {
        self.table.get_key_value(&code).map(|(key, _)| key.clone())
    }

    #[inline]
    fn as_dyn_cons_mut(&mut self) -> &mut dyn ConsCtx {
        self
    }
}

impl TermEqCtxMut for DisjointSetCtx {
    fn term_eq_mut(&mut self, left: &Term, right: &Term) -> Option<bool> {
        //TODO: optimize
        if left == right {
            return Some(true);
        }
        let left = self.get_repr_term_mut(left)?;
        let right = self.get_repr_term_mut(right)?;
        self.repr_eq(left, right)
    }

    fn shallow_cons_term_eq(&mut self, left: &TermId, right: &TermId) -> Option<bool>
    where
        Self: ConsCtx,
    {
        let (left, _left_consed) = self.shallow_cons_index(left);
        let (right, _right_consed) = self.shallow_cons_index(right);
        self.repr_eq(left, right)
    }

    fn deep_cons_term_eq(&mut self, left: &TermId, right: &TermId) -> Option<bool> {
        //TODO: optimize
        let left_consed = left.cons_id(self);
        let right_consed = right.cons_id(self);
        let left = left_consed.as_ref().unwrap_or(left);
        let right = right_consed.as_ref().unwrap_or(right);
        self.term_eq_mut(left, right)
    }

    fn is_ty_mut(&mut self, ty: &Term) -> Option<bool> {
        if let Some(result) = ty.is_local_ty() {
            return Some(result);
        }
        let repr = self.get_repr_term_mut(ty)?;
        if self
            .table
            .get_index(repr)
            .expect("get_repr_term_mut always returns a valid index")
            .1
            .is_ty()
        {
            Some(true)
        } else {
            None
        }
    }

    fn shallow_cons_is_ty(&mut self, ty: &TermId) -> Option<bool> {
        if let Some(result) = ty.is_local_ty() {
            Some(result)
        } else {
            let ix = self.shallow_cons_index(ty).0;
            let repr = self.get_repr_index_mut(ix);
            if self
                .table
                .get_index(repr)
                .expect("get_repr_term_mut always returns a valid index")
                .1
                .is_ty()
            {
                Some(true)
            } else {
                None
            }
        }
    }

    fn deep_cons_is_ty(&mut self, ty: &TermId) -> Option<bool> {
        let ty_consed = ty.cons_id(self);
        let ty = ty_consed.as_ref().unwrap_or(ty);
        self.is_ty_mut(ty)
    }

    fn root_mut(&mut self, ty: &Term) -> Option<TermId> {
        if ty.is_root() {
            return None;
        }
        let repr = self.get_repr_term_mut(ty)?;
        let result = self
            .table
            .get_index(repr)
            .expect("get_repr_term_mut always returns a valid index")
            .0;
        if result.as_ptr() == ty as *const _ {
            None
        } else {
            Some(result.clone())
        }
    }

    fn shallow_cons_root(&mut self, ty: &TermId) -> Option<TermId> {
        if ty.is_root() {
            return None;
        }
        let (ix, consed) = self.shallow_cons_index(ty);
        let repr = self.get_repr_index_mut(ix);
        if repr == ix {
            consed
        } else {
            Some(
                self.table
                    .get_index(repr)
                    .expect("get_repr_term_mut always returns a valid index")
                    .0
                    .clone(),
            )
        }
    }

    fn deep_cons_root(&mut self, ty: &TermId) -> Option<TermId> {
        if ty.is_root() {
            return None;
        }
        let ty_consed = ty.cons_id(self);
        let ty = ty_consed.as_ref().unwrap_or(ty);
        self.root_mut(ty)
    }

    #[inline]
    fn as_dyn_eq_mut(&mut self) -> &mut dyn TermEqCtxMut {
        self
    }

    fn approx_term_eq_mut(&mut self, left: &Term, right: &Term) -> Option<Option<bool>> {
        //TODO: fix this...
        Some(self.term_eq_mut(left, right))
    }

    fn approx_term_eq_code(
        &self,
        _left: (Code, Form),
        _right: (Code, Form),
    ) -> Option<Option<bool>> {
        //TODO: fix this...
        None
    }

    #[inline]
    fn cache_eq(&mut self, left: &TermId, right: &TermId) {
        self.make_term_eq(left, right);
    }

    #[inline]
    fn shallow_cons_cache_eq(&mut self, left: &TermId, right: &TermId) {
        self.shallow_cons_make_term_eq(left, right);
    }

    #[inline]
    fn cmp_annot(&self) -> bool {
        false
    }

    #[inline]
    fn cmp_param(&self) -> bool {
        true
    }

    #[inline]
    fn cmp_var(&self) -> bool {
        true
    }

    #[inline]
    fn typed_mask(&self) -> L4 {
        L4::Both
    }

    #[inline]
    fn untyped_mask(&self) -> L4 {
        L4::True
    }

    #[inline]
    fn is_struct(&self) -> bool {
        false
    }
}

impl TermEqCtx for DisjointSetCtx {
    fn term_eq(&self, left: &Term, right: &Term) -> Option<bool> {
        if left as *const _ == right as *const _ {
            return Some(true);
        }
        let left = self.get_repr_term(left)?;
        let right = self.get_repr_term(right)?;
        self.repr_eq(left, right)
    }

    fn is_ty(&self, ty: &Term) -> Option<bool> {
        if let Some(result) = ty.is_local_ty() {
            Some(result)
        } else if let Some(repr) = self.get_repr_term(ty) {
            let entry = self
                .table
                .get_index(repr)
                .expect("get_repr_term_mut always returns a valid index");
            if entry.1.is_ty() {
                Some(true)
            } else {
                entry.0.is_local_ty()
            }
        } else {
            None
        }
    }

    fn universe(&self, ty: &Term) -> Option<Universe> {
        if let Some(universe) = ty.universe() {
            Some(universe)
        } else if let Some(repr) = self.get_repr_term(ty) {
            self.table
                .get_index(repr)
                .expect("get_repr_term_mut always returns a valid index")
                .0
                .universe()
        } else {
            None
        }
    }
}

impl TermEqCtxEdit for DisjointSetCtx {
    fn make_term_eq(&mut self, left: &TermId, right: &TermId) -> bool {
        //TODO: optimize
        let left_consed = left.cons_id(self);
        let right_consed = right.cons_id(self);
        let left = left_consed.as_ref().unwrap_or(left);
        let right = right_consed.as_ref().unwrap_or(right);
        if left == right {
            return true;
        }
        let result = self.shallow_cons_make_term_eq(left, right);
        debug_assert_eq!(self.term_eq(left, right), Some(true));
        result
    }

    fn shallow_cons_make_term_eq(&mut self, left: &TermId, right: &TermId) -> bool {
        let (left_ix, _left_consed) = self.shallow_cons_index(left);
        let (right_ix, _right_consed) = self.shallow_cons_index(right);
        let result = self.merge_indices(left_ix, right_ix);
        debug_assert_eq!(self.term_eq(left, right), Some(true));
        result
    }
}

#[cfg(test)]
pub mod test {
    use super::*;
    use crate::term::Code;
    use term::dynamic::DebugValue;

    pub fn basic_universe_test(ctx: &mut impl ConsCtx) {
        let set = Universe::set();
        let set_id = set.clone_into_id_direct();
        debug_assert!(!ctx.check_cons(&set_id));
        debug_assert_eq!(ctx.try_cons(&set_id), Err(()));
        let set_id_ctx = set.clone_into_id_with(ctx);
        debug_assert!(ctx.check_cons(&set_id_ctx));
        debug_assert_eq!(ctx.try_cons(&set_id_ctx), Ok(None));
        debug_assert!(set_id.ptr_eq(&set_id_ctx) || !ctx.check_cons(&set_id));
        debug_assert!(
            set_id.ptr_eq(&set_id_ctx) || ctx.try_cons(&set_id).unwrap().unwrap() == set_id_ctx
        );
    }

    pub fn basic_hash_collision_test(code: Code, ctx: &mut impl ConsCtx) {
        let pair = |name| {
            let debug = DebugValue::code(name, code).into_dyn_term();
            (debug.clone().into_id_direct(), debug.into_id_direct())
        };
        let twos = [pair("x"), pair("y"), pair("z")];
        for (i, (ai, bi)) in twos.iter().enumerate() {
            assert_eq!(ai, bi);
            assert_ne!(ai.as_ptr(), bi.as_ptr());
            for (j, (aj, bj)) in twos.iter().enumerate() {
                if i == j {
                    assert_eq!(ai, aj);
                    assert_eq!(bi, bj);
                } else {
                    assert_ne!(ai, aj);
                    assert_ne!(bi, bj);
                }
            }
        }
        for (a, b) in &twos {
            assert_eq!(a.cons_id(ctx), None);
            assert_eq!(a.cons_id(ctx), None);
            assert_eq!(b.cons_id(ctx).as_ref(), Some(a))
        }
        for (a, b) in &twos {
            assert_eq!(a.cons_id(ctx), None);
            assert_eq!(a.cons_id(ctx), None);
            assert_eq!(b.cons_id(ctx).as_ref(), Some(a))
        }
    }

    pub fn basic_equality_test(ctx: &mut (impl TermEqCtxEdit + TermEqCtx)) {
        let values = [
            DebugValue::name_id("0"),
            DebugValue::name_id("1"),
            DebugValue::name_id("2"),
            DebugValue::name_id("3"),
            DebugValue::name_id("4"),
            DebugValue::name_id("5"),
            DebugValue::name_id("6"),
            DebugValue::name_id("7"),
            DebugValue::name_id("8"),
            DebugValue::name_id("9"),
        ];
        for (i, vi) in values.iter().enumerate() {
            for (j, vj) in values.iter().enumerate() {
                if i == j {
                    assert_eq!(vi, vj);
                    assert_eq!(ctx.term_eq(vi, vj), Some(true));
                } else {
                    assert_ne!(vi, vj);
                    assert_eq!(ctx.term_eq(vi, vj), None);
                }
            }
        }
        assert!(!ctx.make_term_eq(&values[0], &values[1]));
        assert!(!ctx.make_term_eq(&values[2], &values[3]));
        assert!(!ctx.make_term_eq(&values[5], &values[6]));
        assert!(!ctx.make_term_eq(&values[7], &values[5]));
        assert!(ctx.make_term_eq(&values[5], &values[7]));
        assert!(!ctx.make_term_eq(&values[2], &values[4]));
        assert!(!ctx.make_term_eq(&values[5], &values[8]));
        for i in 0..=1 {
            for j in 0..=1 {
                if i == j {
                    assert_eq!(values[i], values[j]);
                } else {
                    assert_ne!(values[i], values[j]);
                    assert_ne!(values[j], values[i]);
                }
                assert_eq!(ctx.term_eq(&values[i], &values[j]), Some(true));
            }
            for j in 2..10 {
                assert_ne!(values[i], values[j]);
                assert_ne!(values[j], values[i]);
                //FIXME: this
                assert_ne!(ctx.term_eq(&values[i], &values[j]), Some(true));
            }
        }
        for i in 2..=4 {
            for j in 2..=4 {
                if i == j {
                    assert_eq!(values[i], values[j])
                } else {
                    assert_ne!(values[i], values[j])
                }
                assert_eq!(ctx.term_eq(&values[i], &values[j]), Some(true));
            }
            for j in 5..10 {
                assert_ne!(values[i], values[j]);
                assert_ne!(values[j], values[i]);
                //FIXME: this
                assert_ne!(ctx.term_eq(&values[i], &values[j]), Some(true));
            }
        }
        for i in 5..=8 {
            for j in 5..=8 {
                if i == j {
                    assert_eq!(values[i], values[j])
                } else {
                    assert_ne!(values[i], values[j])
                }
                assert_eq!(ctx.term_eq(&values[i], &values[j]), Some(true));
            }
            for j in 9..10 {
                assert_ne!(values[i], values[j]);
                assert_ne!(values[j], values[i]);
                assert_eq!(ctx.term_eq(&values[i], &values[j]), None);
            }
        }
    }

    #[test]
    fn basic_universe_ctx() {
        let mut ctx = DisjointSetCtx::default();
        basic_equality_test(&mut ctx)
    }

    #[test]
    fn basic_hash_collision_ctx() {
        let mut ctx = DisjointSetCtx::default();
        // NOTE: unlike the weak tests, repetitions are removed, as otherwise the test will fail since the standard context holds *strong* references.
        // Post note: there used to be a weak context, to which the "weak tests" refer to. Will probably be added back in as a separate model.
        debug_assert_eq!(ctx.len(), 0);
        basic_hash_collision_test(Code::new(0x10, 0x0), &mut ctx);
        debug_assert_eq!(ctx.len(), 3);
        basic_hash_collision_test(Code::new(0x20, 0x0), &mut ctx);
        debug_assert_eq!(ctx.len(), 6);
        basic_hash_collision_test(Code::new(0x30, 0x0), &mut ctx);
        debug_assert_eq!(ctx.len(), 9);
        basic_hash_collision_test(Code::new(0x40, 0x0), &mut ctx);
        debug_assert_eq!(ctx.len(), 12);
    }

    #[test]
    fn basic_equality_ctx() {
        let mut ctx = DisjointSetCtx::default();
        basic_equality_test(&mut ctx);
    }
}